package com.wgn.reportquery.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipInputStream;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;

/**
 * @author liuBf 类说明:解压文件公用类
 * 
 */

public class UnzipUtils {

	/*** 这里用到了synchronized ，也就是防止出现并发问题 ***/
	public static synchronized void untar(String tarFileName, String extPlace)
			throws Exception {
		unRarFile(tarFileName, extPlace);
	}

	public static synchronized void unzip(String zipFileName, String extPlace)
			throws Exception {
		unZipFiles(zipFileName, extPlace);
	}

	

	public static synchronized List<InputStream> unzip(String zipFileName)
			throws Exception {

		System.setProperty("sun.zip.encoding",
				System.getProperty("sun.jnu.encoding"));
		try {

			File f = new File(zipFileName);
			ZipFile zipFile = new ZipFile(zipFileName, "GBK"); // 处理中文文件名乱码的问题
			if ((!f.exists()) && (f.length() <= 0)) {
				throw new Exception("要解压的文件不存在!");
			}

			Enumeration<?> e = zipFile.getEntries();
			List<InputStream> iss = new ArrayList();
			while (e.hasMoreElements()) {
				ZipEntry zipEnt = (ZipEntry) e.nextElement();
				if (zipEnt.isDirectory()) {
					// strtemp = strPath + File.separator + gbkPath;
					// File dir = new File(strtemp);
					// dir.mkdirs();
					// continue;
				} else {
					// 读文件流
					InputStream is = zipFile.getInputStream(zipEnt);
					iss.add(is);

				}
			}
			return iss;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * 解压zip格式的压缩文件到指定位置
	 * 
	 * @param zipFileName
	 *            压缩文件
	 * @param extPlace
	 *            解压目录
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static boolean unZipFiles(String zipFileName, String extPlace)
			throws Exception {
		System.setProperty("sun.zip.encoding",
				System.getProperty("sun.jnu.encoding"));
		try {
			(new File(extPlace)).mkdirs();
			File f = new File(zipFileName);
			ZipFile zipFile = new ZipFile(zipFileName, "GBK"); // 处理中文文件名乱码的问题
			if ((!f.exists()) && (f.length() <= 0)) {
				throw new Exception("要解压的文件不存在!");
			}
			String strPath, gbkPath, strtemp;
			File tempFile = new File(extPlace);
			strPath = tempFile.getAbsolutePath();
			Enumeration<?> e = zipFile.getEntries();
			while (e.hasMoreElements()) {
				ZipEntry zipEnt = (ZipEntry) e.nextElement();
				gbkPath = zipEnt.getName();
				if (zipEnt.isDirectory()) {
					strtemp = strPath + File.separator + gbkPath;
					File dir = new File(strtemp);
					dir.mkdirs();
					continue;
				} else {
					// 读写文件
					InputStream is = zipFile.getInputStream(zipEnt);
					BufferedInputStream bis = new BufferedInputStream(is);
					gbkPath = zipEnt.getName();
					strtemp = strPath + File.separator + gbkPath;

					// 建目录
					String strsubdir = gbkPath;
					for (int i = 0; i < strsubdir.length(); i++) {
						if (strsubdir.substring(i, i + 1).equalsIgnoreCase("/")) {
							String temp = strPath + File.separator
									+ strsubdir.substring(0, i);
							File subdir = new File(temp);
							if (!subdir.exists())
								subdir.mkdir();
						}
					}
					FileOutputStream fos = new FileOutputStream(strtemp);
					BufferedOutputStream bos = new BufferedOutputStream(fos);
					int c;
					while ((c = bis.read()) != -1) {
						bos.write((byte) c);
					}
					bos.close();
					fos.close();
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public static boolean unZipFiles(String zipFileName, String extPlace,
			InputStream zipstream) throws Exception {
		System.setProperty("sun.zip.encoding",
				System.getProperty("sun.jnu.encoding"));
		try {

			// get a ZipFile instance
			ZipInputStream zis = new ZipInputStream(zipstream);
			java.util.zip.ZipEntry entry = null;
			// a circle to get every file
			while ((entry = zis.getNextEntry()) != null) {
				System.out.println("decompress file :" + entry.getName());

				// define the path to set the file
				File outFile = new File(extPlace + File.separator
						+ entry.getName());

				// if the file not exits ,than create the file
				if (!outFile.exists()) {
					outFile.createNewFile();
				}

				// create an output stream
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(outFile));
				byte[] b = new byte[100];
				while (true) {
					int len = zipstream.read(b);
					if (len == -1)
						break;
					bos.write(b, 0, len);
				}
				// close stream
				bos.close();
			}
			zis.close();

			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 根据原始rar路径，解压到指定文件夹下.
	 * 
	 * @param srcRarPath
	 *            原始rar路径
	 * @param dstDirectoryPath
	 *            解压到的文件夹
	 */
	public static void unRarFile(String srcRarPath, String dstDirectoryPath) {
		if (!srcRarPath.toLowerCase().endsWith(".rar")) {
			System.out.println("非rar文件！");
			return;
		}
		File dstDiretory = new File(dstDirectoryPath);
		if (!dstDiretory.exists()) {// 目标目录不存在时，创建该文件夹
			dstDiretory.mkdirs();
		}
		Archive a = null;
		try {
			a = new Archive(new File(srcRarPath));
			if (a != null) {
				// a.getMainHeader().print(); // 打印文件信息.
				FileHeader fh = a.nextFileHeader();

				while (fh != null) {

					// 防止文件名中文乱码问题的处理

					String fileName = fh.getFileNameW().isEmpty() ? fh
							.getFileNameString() : fh.getFileNameW();
					if (fh.isDirectory()) { // 文件夹
						File fol = new File(dstDirectoryPath + File.separator
								+ fileName);
						fol.mkdirs();
					} else { // 文件
						File out = new File(dstDirectoryPath + File.separator
								+ fileName.trim());
						try {
							if (!out.exists()) {
								if (!out.getParentFile().exists()) {// 相对路径可能多级，可能需要创建父目录.
									out.getParentFile().mkdirs();
								}
								out.createNewFile();
							}
							FileOutputStream os = new FileOutputStream(out);
							a.extractFile(fh, os);
							os.close();
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}
					fh = a.nextFileHeader();
				}
				a.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 作者：hellostory 时间：2010-11-30 16:37
	 * 
	 * @throws Exception
	 */
	public static File inputstream2File(InputStream ins, String fileName)
			throws Exception {

		File file = new File(fileName);
		FileOutputStream fos = null;

		// 这里对is进行赋值，略
		// ...

		// 文件输出流fos
		// openFile()为自定义函数，判断文件是否存在等（略）

		try {
			// 打开一个已存在文件的输出流
			fos = new FileOutputStream(file);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 将输入流is写入文件输出流fos中
		int ch = 0;
		try {
			while ((ch = ins.read()) != -1) {
				fos.write(ch);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			// 关闭输入流等（略）
			fos.close();

		}

		return file;
	}

	public static void inputstreamtofile(InputStream ins, File file) {
		try {
			OutputStream os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}